package com.leyou.cart.controller;

import com.leyou.cart.Service.CartService;
import com.leyou.cart.pojo.CartSon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping
    public ResponseEntity<Void> addCart(@RequestBody CartSon cart) {
        this.cartService.addCart(cart);
        return ResponseEntity.ok().build();
    }

    @GetMapping
    public ResponseEntity<List<CartSon>> queryCartList() {
        List<CartSon> carts = this.cartService.queryCartList();

        if (CollectionUtils.isEmpty(carts)) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        return ResponseEntity.ok(carts);
    }

    @PutMapping
    public ResponseEntity<Void> updateNum(@RequestBody CartSon cart) {
        this.cartService.updateNum(cart);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("{id}")
    public ResponseEntity<Void> deleteCart(@PathVariable("id") Long id) {
        this.cartService.deleteCart(id);
        return ResponseEntity.ok().build();
    }

    @PostMapping("merge")

    public ResponseEntity<List<CartSon>> mergeCarts(@RequestBody List<CartSon> carts) {
        Boolean aBoolean = this.cartService.mergeCarts(carts);
        if (!aBoolean) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        List<CartSon> list = this.cartService.queryCartList();
        return ResponseEntity.ok(list);
    }
}

